<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import { userPasswordUpdateService } from '@/api/user.js'
//定义绑定参数数据
const updatePwData = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})
//自定义确认密码的校验函数
const rePasswordValid = (rule, value, callback) => {
    if (value == null || value === '') {
        return callback(new Error('请再次确认密码'))
    } else if (updatePwData.value.password !== value) {
        return callback(new Error('两次输入密码不一致'))
    } else {
        return callback()
    }
}
const rules = ref({
    old_pwd: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 5, max: 16, message: '原密码长度必须为5~16位', trigger: 'blur' }
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '新密码长度必须为5~16位', trigger: 'blur' }
    ],
    re_pwd: [
        { validator: rePasswordValid, trigger: 'blur' }
    ]
})
import { useUserInfoStore } from '@/stores/userInfo';
import { useTokenStore } from '@/stores/token';
import router from '@/router';
const userInfoStore = useUserInfoStore();
const tokenStore = useTokenStore();
// 在修改密码成功后，把pinia内的所有数据全部清空之后跳转到登录页面
const updatePassword = async () => {
    let result = await userPasswordUpdateService(updatePwData.value);
    ElMessage.success('修改成功！');
    ElMessage.success('请重新登录！')
    // 清空pinia库数据
    userInfoStore.removeInfo();
    tokenStore.removeToken();
    // 跳转到登录页面
    router.push('/login');
}
// 绑定重置密码即将输入信息清空
const clearPasswordData = () => {
    updatePwData.value.old_pwd = '';
    updatePwData.value.new_pwd = '';
    updatePwData.value.re_pwd = '';
}

</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>更改密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form :model="updatePwData" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="原密码" prop="old_pwd">
                        <el-input v-model="updatePwData.old_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input v-model="updatePwData.new_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="re_pwd">
                        <el-input v-model="updatePwData.re_pwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updatePassword">更改密码</el-button>
                        <el-button type="defaule" @click="clearPasswordData">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>